<template>
  <div>
    <Row :gutter="4" >
      <Col span="2"><Button @click="argGisTiles">ArcGIS瓦片服务器</Button></Col>
      <Col span="2">
        <Select v-model="customMap" placeholder="地图选择" @on-change="customMapChange">
          <Option v-for="item in customMaps" :value="item.name" :key="item.name">{{ item.desc }}</Option>
        </Select>
      </Col>
      <Col span="1" v-if="!isRanging"><Button @click="rangeStart">测距</Button></Col>
      <Col span="1" v-if="isRanging"><Button @click="rangeStart">结束测距</Button></Col>

      <Col span="1" v-if="!isPolygon"><Button @click="polygonStart">画多边形</Button></Col>
      <Col span="1" v-if="isPolygon"><Button @click="polygonStart">多边形结束</Button></Col>

      <Col span="1" v-if="!isCircle"><Button @click="circleStart">画园形</Button></Col>
      <Col span="1" v-if="isCircle"><Button @click="circleStart">园形结束</Button></Col>

      <Col span="1" v-if="!isLine"><Button @click="lineStart">画直线</Button></Col>
      <Col span="1" v-if="isLine"><Button @click="lineStart">直线结束</Button></Col>


      <Col span="1" ><Button @click="changeStyle">改样式</Button></Col>

      <Col span="1" ><Button @click="getlocation">拾取定位</Button></Col>

      <Col span="2"><Button @click="attributions">控制Controls组件</Button></Col>
      <Col span="1"><Button @click="flyToLondon">飞到london</Button></Col>

      <Col span="1"><Button @click="debugTiles">调试瓦片</Button></Col>
      <Col span="1"><Button @click="getZoom">地图级别</Button></Col>

      <Col span="1" ><Button @click="changeMapInSub">子件换地图</Button></Col>
      <Col span="3" >
        <input v-model="location" :style="{width:'100px'}"></input>
        <Button @click="goto">定位</Button>
      </Col>

    </Row>
    <Row :gutter="4" >
      <Col span="12" >
<!--        <input v-model="locationBd" :style="{width:'150px'}" placeholder="百度坐标"></input>
        <input v-model="location84" :style="{width:'150px'}" placeholder="天地图坐标"></input>
        <input v-model="locationGcj" :style="{width:'150px'}" placeholder="高德坐标"></input>
        <Button @click="">计算并定位</Button>-->
      </Col>
    </Row>
    <div id="map" ref="map" :style="{backgroud: '#000000'}"></div>


    <!-- 右边 -->
    <DrawerRightButton @click="drawerRightBtnClick"
                       :display="drawerRightBtnDisplay"
                       :boxHeight="drawerRight.drawerHeight"
                       :boxWidth="drawerRight.drawerWidth" ></DrawerRightButton>
    <DrawerRight title="云台控制"
                 :display="drawerRightDisplay"
                 :width="drawerRight.drawerWidth"
                 :height="drawerRight.drawerHeight"
                 :inner="drawerRight.inner"
                 :mask="drawerRight.mask"
                 @close="drawerRightClick">
    </DrawerRight>

    <!-- 地图工具：地图切换，绘制，测距 -->
    <MapTools ref="downPopupMenu" :map="map" :mapElement="mapId" :drawing="drawing"></MapTools>


  </div>
</template>
<script>
import DrawerRightButton from './DrawerRightButton';
import DrawerRight from './DrawerRight';
import FloatingPanel from "./FloatingPanel";
import MapTools from "./maptools/MapTools";
import  "ol/ol.css";
import TileLayer from "ol/layer/Tile";

/**
 * *  这样使用就报错：error  in ./node_modules/geotiff/dist-module/geotiff.js
 *  import {OSM, TileArcGISRest} from 'ol/source';
 */
import OSM from "ol/source/OSM";
import TileArcGISRest from "ol/source/TileArcGISRest";
import TileImage from "ol/source/TileImage";
import XYZ from "ol/source/XYZ";
import TileDebug from "ol/source/TileDebug";
import { Map, View,Feature } from "ol";
import {Attribution, defaults as defaultControls} from 'ol/control';
import {addProjection, addCoordinateTransforms, transform, fromLonLat, transformExtent} from 'ol/proj';
import ImageLayer from 'ol/layer/Image';
import Raster from 'ol/source/Raster';
//import {Raster as RasterSource, Stamen} from 'ol/source';

//import {TileGrid} from "ol/tilegrid.js";
import TileGrid from "ol/src/tilegrid/TileGrid.js";

import LayerVector from "ol/layer/Vector.js";
import SourceVector from "ol/source/Vector.js";

import Point from "ol/geom/Point"
import Projection from "ol/proj/Projection";

import Ranging from "./maptools/Ranging";
import PaintTools from './maptools/PaintTools';

import {polygonStyle,pointStyle} from './maptools/style'
import RangeingToolTip from "./maptools/RangingToolTip";
import ToolTip from "./maptools/ToolTip";
import {lngLatToMercator,mercatorToLngLat} from './maptools/tool/BD09';
import GPS from './maptools/tool/Gps';

/** 使用 gcoord 转换 WGS84、GCJ-02、BD09、EPSG4326 */
import gcoord from 'gcoord';


export default {
  components:{DrawerRightButton,DrawerRight,FloatingPanel,MapTools},

  data() {
    return {
      gps: new GPS(),
      points:[],
      drawing:{
        drawing:false,
        name:"结束"
      },
      isBaidu: false,
      //location: '101.84733553152822, 26.683028004383928',
      location: '114.237961, 22.684879', //天地图：深圳龙岗嶂背步行街坐标
      //location: '101.8470129413785, 26.68303495430042', //天地图，攀枝花盐边县人民医院坐标
      //101.856166, 26.685485
      tooltip1: null,
      mapId: 'map',
      panelHeight: '100px',
      panelWidth: '48px',

      ranging: new Ranging(), //是否正在测距
      isRanging: false,
      paintTools: new PaintTools(), //画图
      isPolygon: false,

      isCircle: false,
      isLine: false,


      projection: "EPSG:4326",
      center: [114.236262, 22.677236],
      //center: [114.237961, 22.684879],
      zoom:14,
      view: null,
      map: null,
      customMap:'BaiduBd09',
      customMaps:[
        {name:'GaodeOffline',desc:'高德离线',coordinateType:'GCJ02'},
        {name:'BaiduBd09',desc:'百度地图',coordinateType:'BD09'},
        //{name:'Baidu6',desc:'百度地图'},

        {name:'DiandiHX',desc:'天地图卫星图',coordinateType:'WGS84'},
        {name:'DiandiHXBJ',desc:'天地图卫星图注记',coordinateType:'WGS84'},
        {name:'DiandiJD',desc:'天地图街道图',coordinateType:'WGS84'},
        {name:'DiandiJDBJ',desc:'天地图街道图注记',coordinateType:'WGS84'},
        {name:'DiandiDX',desc:'天地图地形图',coordinateType:'WGS84'},
        {name:'ArcgisYX',desc:'arcgis影像地图',coordinateType:'WGS84'},
        {name:'ArcgisJD',desc:'arcgis街景地图',coordinateType:'WGS84'},
        {name:'GoogleYX',desc:'谷歌影像地图',coordinateType:'GCJ02'},
        {name:'GoogleJD',desc:'谷歌街景地图',coordinateType:'GCJ02'},
        {name:'GaodeYX',desc:'高德影像地图',coordinateType:'GCJ02'},
        {name:'GaodeJD',desc:'高德街景地图',coordinateType:'GCJ02'},
        {name:'OSM',desc:'OSM',coordinateType:'WGS84'},
        {name:'BingMaps',desc:'必应地图',coordinateType:'WGS84'},
        {name:'BaiduOffline',desc:'百度离线',coordinateType:'BD09'},
        {name:'BaiduOffline1',desc:'百度离线无偏移',coordinateType:'BD09'},

        //{name:'Baidu',desc:'百度地图'},
      ],
      drawerRight:{
        drawerHeight:'60%',
        drawerWidth:'200px',
        inner:false,
        display: false,
        mask: false,
      },

      customLayers:{
        /**layer：层
         contorl：控件
         feature：元素
         interaction：交互
         Vector：矢量的
         Tile：瓦片
         source：资源
         format：转换
         projection：投影
         */
        layerVector: new LayerVector(),  //me.all_obj.monitor.layer
        sourceVector: new SourceVector(), //me.all_obj.monitor.data_c

/*        me.all_obj.monitor.layer = new ol.layer.Vector();
        me.all_obj.monitor.data_c = new ol.source.Vector();
        me.all_obj.monitor.layer.setSource(me.all_obj.monitor.data_c);
        me.all_obj.monitor.layer.setStyle(polygon_style());
        me.map.addLayer(me.all_obj.monitor.layer);

        me.all_obj.popup.element = document.createElement("div");
        me.all_obj.popup.popup = new ol.Overlay({
          element: me.all_obj.popup.element,
          positioning: 'bottom-center',
          stopEvent: false,
          offset: [0, -50]
        });
        me.map.addOverlay(me.all_obj.popup.popup);*/
      }
    };
  },
  created() {},
  mounted() {

    this.customLayers.layerVector.setSource(this.customLayers.sourceVector);
    this.customLayers.layerVector.setStyle(polygonStyle);
    this.initMap();
/*
    console.log(this.map);
    console.log(this.customLayers);
    this.map.addLayer(this.customLayers.layerVector);
    console.log("2");
*/
  },
  methods: {
    debugTiles(){
      //调试瓦片
      const that = this;
      let layers=[];
      let view=null;
      layers = [
        new TileLayer({
          source: new OSM(),
        }),
        /** 调试 模式 */
        new TileLayer({
          source: new TileDebug(),
        }),
      ];
      view = new View({
        projection: that.projection,
        center: that.center,
        zoom: 5,
      });
      //移除老的layers
      let lastLayers = this.map.getLayerGroup().getLayers().getArray();
      for(let i=lastLayers.length-1;i>=0;i--){
        that.map.removeLayer(lastLayers[i]);
      }
      that.map.setLayers(layers);
      that.map.setView(view);


    },
    getZoom(){
      /** 不带 “地图级别”就不能显示数字*/
      this.$Message.info("地图级别："+this.map.getView().getZoom());
    },
    changeMapInSub(){
      this.$refs.downPopupMenu.changeMap();
    },
    /**
     * 必应地图，此例子可切换不同的地图
     * 这个例子展示了如何动态显示、隐藏地图的层 ( layers )，主要用到的是 setVisible方法。
     * https://openlayers.org/en/latest/examples/bing-maps.html
     */
    customMapChange(){
      //console.log("customMapChange：%o",this.customMap);
      this.isBaidu=false;
      const that = this;
      let layers=[];
      let view=null;
      // OSM 地图
      if (this.customMap == 'OSM'){
        layers = [
          new TileLayer({
            source: new OSM(),
          })];
        view = new View({
          projection: that.projection,
          center: that.center,
          zoom: that.zoom,
        });

      }else if (this.customMap == 'BaiduOffline1') {
        this.isBaidu=true;
        // 百度离线无偏移
        const projBD09 = new Projection({
          code: 'BD:09',
          extent : [-20037726.37,-11708041.66,20037726.37,12474104.17],
          units: 'm',
          axisOrientation: 'neu',
          global: false
        });
        addProjection(projBD09);
        addCoordinateTransforms("EPSG:4326", "BD:09",
          function (coordinate) {
            return lngLatToMercator(coordinate);
          },
          function (coordinate) {
            return mercatorToLngLat(coordinate);
          }
        );
        /*定义百度地图分辨率与瓦片网格*/
        var resolutions = [];
        for (var i = 0; i <= 18; i++) {
          resolutions[i] = Math.pow(2, 18 - i);
        }
        //天地图 盐边县人民医院 坐标
        const yanbian = [101.84735638541707, 26.68304902844003];

        var tilegrid = new TileGrid({
          origin: yanbian,
          resolutions: resolutions
        });

        var baiduSource = new TileImage({
          projection: "BD:09",
          tileGrid: tilegrid,
          tileUrlFunction: function(tileCoord, pixelRatio, proj) {
            var z = tileCoord[0];
            var x = tileCoord[1];
            var y = -tileCoord[2]-1;
            return "http://localhost:8081/map/"+z+"/"+x+"/"+y+".png"
          }
        });

        // 百度地图层
        layers = [
          new TileLayer({
            source: baiduSource,
          })];
        view = new View({
          zoom: that.zoom,
          projection: 'BD:09',
          center : transform(yanbian, 'EPSG:4326', 'BD:09'),
        })

/*        new ol.Map({
          layers: [
            mapLayer
          ],
          view: new ol.View({
            center: ol.proj.transform([113.03914, 28.20354], 'EPSG:4326', 'BD:09'),
            projection: 'BD:09',
            zoom: 14
          }),
          target: 'map'
        });*/

      }else if (this.customMap == 'BaiduOffline'){
        ;
        // 百度离线
      }else if(this.customMap == 'BaiduProjzh') {
        /** 使用 Projzh 加载百度地图 */

      }else if(this.customMap == 'BaiduBd09') {
        this.isBaidu=true;
        //百度地图无偏移
        const projBD09 = new Projection({
          code: 'BD:09',
          extent : [-20037726.37,-11708041.66,20037726.37,12474104.17],
          units: 'm',
          axisOrientation: 'neu',
          global: false
        });



        addProjection(projBD09);
        addCoordinateTransforms("EPSG:4326", "BD:09",
          function (coordinate) {
            return lngLatToMercator(coordinate);
          },
          function (coordinate) {
            return mercatorToLngLat(coordinate);
          }
        );
        let resolutions = [];
        const maxZoom = 18;
        // 计算百度使用的分辨率
        for(let i=0; i<=maxZoom; i++){
          resolutions[i] = Math.pow(2, maxZoom-i);
        }
        const tilegrid  = new TileGrid({
          origin: that.center,    // 设置原点坐标
          resolutions: resolutions    // 设置分辨率
        });
        var baiduSource = new TileImage({
          projection: "BD:09",
          tileGrid: tilegrid,
          tileUrlFunction: function(tileCoord, pixelRatio, proj) {
            var z = tileCoord[0];
            var x = tileCoord[1];
            //var y = -tileCoord[2];
            var y = -tileCoord[2];
            // 百度瓦片服务url将负数使用M前缀来标识
            if(x<0){ x = 'M' + (-x); }
            if(y<0){ y = 'M' + (-y); }
            return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1";
          }
        });

        console.log(transform([-20037726.37,-11708041.66],'BD:09','EPSG:4326'));
        console.log(transform([20037726.37,12474104.17],'BD:09','EPSG:4326'));

        // 百度地图层
        layers = [
          new TileLayer({
            source: baiduSource,
          })];
        view = new View({
          zoom: that.zoom,
          projection: 'BD:09',
          center : transform(that.center,'EPSG:4326', 'BD:09'),
        })

      }else if(this.customMap == 'Baidu6'){
        console.log("百度地图");
        this.isBaidu=false;
        let resolutions = [];
        const maxZoom = 18;
        // 计算百度使用的分辨率
        for(let i=0; i<=maxZoom; i++){
          resolutions[i] = Math.pow(2, maxZoom-i);
        }
        const tilegrid  = new TileGrid({
          origin: that.center,    // 设置原点坐标
          resolutions: resolutions    // 设置分辨率
        });

        // 创建百度地图的数据源
        const baiduSource = new TileImage({
          projection: 'EPSG:3857',
          //projection: 'BD:09',
          tileGrid: tilegrid,
          tileUrlFunction: function(tileCoord, pixelRatio, proj){
            if (!tileCoord){
              return '';
            }
            let z = tileCoord[0];
            let x = tileCoord[1];
            /** openlayers6 版本这里要这样改才能解决
             * 由于openlayers6加载地图的方式是右下递增，原先是右上递增，所以在原先加载百度地图的基础之上，将tileUrlFunction中的y坐标变为原先的相反数即可。
             * https://blog.csdn.net/weixin_43685945/article/details/107152863
             *
              *https://www.giserdqy.com/secdev/openlayers/36281/
             **/
            //let y = tileCoord[2];
            //let y = -tileCoord[2]-1;
            let y = -tileCoord[2];

            // 百度瓦片服务url将负数使用M前缀来标识
/*            if(x<0){
              x = 'M' + (-x);
            }
            if(y<0){
              y = 'M' + (-y);
            }*/

            //return "http://online0.map.bdimg.com/onlinelabel/?qt=tile&x="+x+"&y="+y+"&z="+z+"&styles=pl&udt=20151021&scaler=1&p=1";
            //return "http://maponline0.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&scaler=1&udt=20210506&from=jsapi3_0";
            return "http://online3.map.bdimg.com/onlinelabel/?qt=tile&x=" + x + "&y=" + y + "&z=" + z + "&styles=pl&udt=20151021&scaler=1&p=1";

          }
        });
        // 百度地图层
        layers = [
          new TileLayer({
            source: baiduSource,
          })];

        view = new View({
          zoom: that.zoom,
          //projection: 'EPSG:3857',
          projection: 'EPSG:4326',
          center : that.center,
        })
      }else if (this.customMap == "GaodeYX"){
        let gdsource = new XYZ({
          url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "GaodeJD"){
        let gdsource = new XYZ({
          url: 'http://webrd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "GoogleYX"){
        let gdsource = new XYZ({
          url: 'http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "GoogleJD"){
        let gdsource = new XYZ({
          url: 'http://www.google.cn/maps/vt?lyrs=m@189&gl=cn&x={x}&y={y}&z={z}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "ArcgisYX"){
        let gdsource = new XYZ({
          url: 'https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "ArcgisJD"){
        let gdsource = new XYZ({
          url: 'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer/tile/{z}/{y}/{x}'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "DiandiHX"){
        let gdsource = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        let gdsource1 = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        layers = [new TileLayer({
          source: gdsource,
        }),

          new TileLayer({
            source: gdsource1,
          }),
        ];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "DiandiHXBJ"){
        let gdsource = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "DiandiJD"){
        let gdsource = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        let gdsource1 = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })

        layers = [new TileLayer({
          source: gdsource,
        }),
          new TileLayer({
            source: gdsource1,
          })
        ];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }else if (this.customMap == "DiandiJDBJ"){
        let gdsource = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        layers = [new TileLayer({
          source: gdsource,
        })];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center : that.center,
        })
      }
      else if (this.customMap == "DiandiDX") {
        let gdsource = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=ter_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        let gdsource1 = new XYZ({
          url: 'http://t{0-7}.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=7786923a385369346d56b966bb6ad62f'
        })
        layers = [new TileLayer({
          source: gdsource,
        }),
          new TileLayer({
            source: gdsource1,
          })
        ];
        view = new View({
          zoom: that.zoom,
          projection: that.projection,
          center: that.center,
        })
      }else if (this.customMap == "BaiduTEST"){
        let mapKey = 'IfkNE0XDdoaTwdGGkOWrALDkFZOTI9b8'; // 百度地图key
        let resolutions = [];
        for (let i = 0; i <= 18; i++) {
          resolutions[i] = Math.pow(2, 18 - i);
        }
        let tileGrid = new TileGrid({
          origin: [0,0],
          resolutions: resolutions
        });
        let mapSource = new TileImage({
          //projection: 'BD09',
          projection: 'EPSG:3857',
          tileGrid: tileGrid,
          tileUrlFunction: function (tileCoord) {
            if (!tileCoord) {
              return "";
            }
            let z = tileCoord[0];
            let x = tileCoord[1];
            let y = -tileCoord[2] - 1;
            let urlNum = (Math.abs(x + y) % 4).toString();
            if (x < 0) {
              x = "M" + (-x).toString();
            }
            if (y < 0) {
              y = "M" + (-y).toString();
            }
            return "http://online0.map.bdimg.com/onlinelabel/?qt=tile&x="+x+"&y="+y+"&z="+z+"&styles=pl&udt=20151021&scaler=1&p=1";
            //http://online0.map.bdimg.com/onlinelabel/?qt=tile&x=1450&y=423&z=13&styles=pl&udt=20151021&scaler=1&p=1
            //console.log("https://maponline0.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&ak=" + mapKey + "&styles=pl&scaler=1&udt=" + Date.parse('yyyyMMdd') + "&from=jsapi2_0");
            //return "https://maponline0.bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z + "&ak=" + mapKey + "&styles=pl&scaler=1&udt=20220510&from=jsapi2_0";
                  //https://maponline0.bdimg.com/tile/?qt=vtile&x={x}&y={y}&z={z}&ak={key}&styles=pl&scaler=1&udt=20220115&from=jsapi2_0"
          }
        });
        layers = [new TileLayer({
          source: mapSource
        })];
        view = new View({
          zoom: that.zoom,
          //projection: 'EPSG:3857',
          projection: 'EPSG:4326',
          center : that.center,
        })
      }else if (this.customMap == "GaodeOffline") {
        //高速离线

      }

/*      that.map = new Map({
        target: "map", // 指向对象
        layers: [
          // 图层
          new TileLayer({
            // 这里定义的是平铺图层
            source: new OSM(),
          }),
        ],
        //loadTilesWhileAnimating: true,//支持动画
        view: that.view,
        /!*        view: new View({
                  projection: "EPSG:4326",
                  center: [114.236262, 22.677236],
                  zoom: 10,
                  animate:function(){
                    center:fromLonLat([-0.12755, 51.507222])
                  }
                })*!/
      });*/


      if (!!layers && !!view){
        if (!that.map){
          that.map = new Map({
            target: "map", // 指向对象
            layers: layers,
            loadTilesWhileAnimating: true,//支持动画
            view: view,
          });
          that.map.addLayer(that.customLayers.layerVector);
        }else{
          //移除老的layers
          let lastLayers = this.map.getLayerGroup().getLayers().getArray();
          for(let i=lastLayers.length-1;i>=0;i--){
            console.log(lastLayers[i]);
            that.map.removeLayer(lastLayers[i]);
          }
          //两秒后回新的layers
/*
          setTimeout(()=>{
          },100);
*/
          that.map.setLayers(layers);
          that.map.setView(view);

          that.map.addLayer(that.customLayers.layerVector);
        }
       }
    },
    /**
     * 控制版权归属组件
     * https://openlayers.org/en/latest/examples/attributions.html
     */
    attributions(){
      const that=this;
      //新的版权控件
      var attribution = new Attribution({
        // 折叠
        collapsible: false
      });
      //这里的意思是，使用默认的 controls ，但是把默认的「版权控件」设置为false，隐藏掉了
      //然后使用 .extend 来添加一个新的「版权控件」
      //const controls = defaultControls({attribution: false}).extend([attribution]);

      const controls = this.map.getControls().getArray();
      //先删除，再加入个新的
      for(let i=controls.length-1;i>=0;i--){
        if (controls[i] instanceof Attribution){
          console.log("controls[i]：%o",controls[i])
          this.map.removeControl(controls[i]);
        }
      }
      this.map.addControl(attribution);

    },
    /**
     * ArcGIS瓦片服务器
     * https://openlayers.org/en/latest/examples/arcgis-tiled.html
     * @constructor
     */
    argGisTiles(){
      console.log("argGisTiles");
      const that=this;
      const url =
        'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' +
        'Specialty/ESRI_StateCityHighway_USA/MapServer';
      const layers = [
        new TileLayer({
          source: new OSM(),
        }),
        new TileLayer({
          extent: [-13884991, 2870341, -7455066, 6338219],
          source: new TileArcGISRest({
            url: url,
          }),
        }),
      ];
      //移除老的layers
      let lastLayers = this.map.getLayerGroup().getLayers().getArray();
      for(let i=lastLayers.length-1;i>=0;i--){
        this.map.removeLayer(lastLayers[i]);
      }
      //两秒后回新的layers
      setTimeout(()=>{
        that.map.setLayers(layers)
      },2000);
    },
    /** 动画视图
     *  https://openlayers.org/en/latest/examples/animation.html
     **/
    flyToLondon(){
      /*动画，飞到轮顿*/
      const london = [-0.12755, 51.507222];

      const view = this.map.getView();

      view.animate({
        center: london,
        duration: 2000,
      });

      //this.view.setCenter([-0.12755, 51.507222]);
      this.view.setZoom(5);

    },
    // 初始化地图
    initMap() {
      this.customMapChange();
      return;

      //this.baiduMap();
      //return;
      let that = this;
      this.view = new View({
        projection: that.projection,
        center: that.center,
        zoom: that.zoom,
      });

      that.map = new Map({
        target: "map", // 指向对象
        layers: [
          // 图层
          new TileLayer({
            // 这里定义的是平铺图层
            source: new OSM(),
          }),
        ],
        //loadTilesWhileAnimating: true,//支持动画
        view: that.view,
      });
      this.map.setView(that.view);
    },
    /** 测距 */
    rangeStart(){
      this.isRanging=!this.isRanging;
      if (this.isRanging){
        /* 开始测距 */
        this.ranging.setMap(this.map);
        this.ranging.setLayer(this.customLayers.layerVector);
        this.ranging.setSource(this.customLayers.sourceVector);
        this.ranging.start();
        this.drawing.name='测距结束';
        this.drawing.drawing=true;
      }else{
        /*结束测距*/
        this.ranging.finish();
        this.drawing.drawing=false;
      }

    },
    /** 画多边形 */
    polygonStart(){
      this.isPolygon = !this.isPolygon;
      if (this.isPolygon){
        /*开始画图*/
        this.paintTools.setMap(this.map);
        this.paintTools.setSource(this.customLayers.sourceVector);
        this.paintTools.start("Polygon")
      }else{
        /*开始画图*/
        this.paintTools.finish();
      }
    },

    /** 画直形 */
    lineStart(){
      this.isLine = !this.isLine;
      if (this.isLine){
        /*开始画图*/
        this.paintTools.setMap(this.map);
        this.paintTools.setSource(this.customLayers.sourceVector);
        this.paintTools.start("LineString");
      }else{
        /*开始画图*/
        this.paintTools.finish();
      }
    },


    /** 画园形 */
    circleStart(){
      this.isCircle = !this.isCircle;
      if (this.isCircle){
        /*开始画图*/
        this.paintTools.setMap(this.map);
        this.paintTools.setSource(this.customLayers.sourceVector);
        this.paintTools.start("Circle")
      }else{
        /*开始画图*/
        this.paintTools.finish();
      }
    },

    /** 切换颜色 */
    changeStyle(){
      let lastLayers = this.map.getLayerGroup().getLayers().getArray();
/*      if (lastLayers.length>0){
        lastLayers[0]
      }*/
/*      for(let i=lastLayers.length-1;i>=0;i--){
        this.map.removeLayer(lastLayers[i]);
      }*/

      let layerOrigin = new TileLayer({
        name: "天地图矢量图层",
        source: lastLayers[0]
      });
      console.log(lastLayers[0]);
      //定义颜色转换方法
      let reverseFunc = function (pixelsTemp) {
        //蓝色
        for (var i = 0; i < pixelsTemp.length; i += 4) {
          var r = pixelsTemp[i];
          var g = pixelsTemp[i + 1];
          var b = pixelsTemp[i + 2];
          //运用图像学公式，设置灰度值
          var grey = r * 0.3 + g * 0.59 + b * 0.11;
          //将rgb的值替换为灰度值
          pixelsTemp[i] = grey;
          pixelsTemp[i + 1] = grey;
          pixelsTemp[i + 2] = grey;

          //基于灰色，设置为蓝色，这几个数值是我自己试出来的，可以根据需求调整
          pixelsTemp[i] = 55 - pixelsTemp[i];
          pixelsTemp[i + 1] = 255 - pixelsTemp[i + 1];
          pixelsTemp[i + 2] = 305 - pixelsTemp[i + 2];
        }
      };

      //openlayer 像素转换类，可以直接当做source使用
      const raster = new RasterSource({
        sources: [
          //传入图层，这里是天地图矢量图或者天地图矢量注记
          layerOrigin,
        ],
        //这里设置为image类型，与官方示例不同，优化速度
        operationType: 'image',
        operation: function (pixels, data) {
          //执行颜色转换方法，注意，这里的方法需要使用lib引入进来才可以使用
          reverseFunc(pixels[0].data)
          return pixels[0];
        },
        //线程数量
        threads: 10,
        //允许operation使用外部方法
        lib: {
          reverseFunc: reverseFunc,
        }
      });
      console.log(raster);
      //创建新图层，注意，必须使用 ImageLayer
      let layer = new ImageLayer({
        name: "天地图矢量图层",
        source: raster
      });

      console.log(layer);
      //添加到地图
      this.map.addLayer(layer)
    },

    /** 拾取定位 */
    getlocation(){
      const that = this;

      this.map.on('singleclick',(evt)=>{
        if (this.isBaidu){
          //console.log("百度坐标转EPSG4326");
          console.log(transform(evt.coordinate, 'BD:09','EPSG:4326'));
        }else{
          console.log(evt.coordinate);
        }
      });

      this.map.on('pointermove',(evt)=>{
        if (!that.tooltip1){
          that.tooltip1 = new ToolTip({map: that.map});
        }
        let pos = this.to4326(evt.coordinate);
        if (that.tooltip1){
/*          if (this.isBaidu){
            that.tooltip1.setContent(transform(evt.coordinate, 'BD:09','EPSG:4326'));
          }else{
            that.tooltip1.setContent(evt.coordinate);
          }*/
          that.tooltip1.setContent(pos);
          that.tooltip1.setPosition(evt.coordinate);
        }
      });
    },
    /** 定位到指定 位置*/
    goto(){
      for(let l in this.points){
        this.customLayers.sourceVector.removeFeature(this.points[l]);
      }
      this.points = [];

      let pos2 = this.location.split(",");
      let posGcj02 = this.gps.gps84ToGcj02(parseFloat(pos2[1]),parseFloat(pos2[0]));
      console.log("Gcj02-pos: %o",posGcj02);
      // 高德坐标
      pos = [posGcj02.lon,posGcj02.lat];
      posBd09 = this.from4326(pos);
      this.map.getView().setCenter(posBd09);
      let point1 = new Feature({
        geometry: new Point(posBd09),
        device:{lng:pos[0],lat:pos[1]}
      });
      point1.setStyle(pointStyle('GCJ02:'+pos[0]+","+pos[1]));
      this.customLayers.sourceVector.addFeature(point1);
      this.points.push(point1);

      //return;
      let pos = this.location.split(",");
      let posBd09 = this.from4326(pos);
      this.map.getView().setCenter(posBd09);
      let point = new Feature({
        geometry: new Point(posBd09),
        device:{lng:pos[0],lat:pos[1]}
      });
      point.setStyle(pointStyle('WPS84:'+pos[0]+","+pos[1]));
      this.customLayers.sourceVector.addFeature(point);
      this.points.push(point);



      let posBd = this.gps.gcj02ToBd09(posGcj02.lat,posGcj02.lon);
      console.log("Bd09-pos: %o",posBd);
      let posBd1=gcoord.transform(pos2,    // 经纬度坐标
        gcoord.WGS84,               // 当前坐标系
        gcoord.BD09)
      console.log("gcoord-bd09: %o",posBd1);



/*      // 高德坐标
      pos = [posGcj02.lon,posGcj02.lat];
      posBd09 = this.from4326(pos);
      this.map.getView().setCenter(posBd09);
      let point1 = new Feature({
        geometry: new Point(posBd09),
        device:{lng:pos[0],lat:pos[1]}
      });
      point1.setStyle(pointStyle('GCJ02:'+pos[0]+","+pos[1]));
      this.customLayers.sourceVector.addFeature(point1);
      this.points.push(point1);*/

      // 百度坐标
      pos = [posBd.lon,posBd.lat];
      posBd09 = this.from4326(pos);
      this.map.getView().setCenter(posBd09);
      let point2 = new Feature({
        geometry: new Point(posBd09),
        device:{lng:pos[0],lat:pos[1]}
      });
      point2.setStyle(pointStyle('BD09:'+pos[0]+","+pos[1]));
      this.customLayers.sourceVector.addFeature(point2);
      this.points.push(point2);


    },
    drawerRightBtnClick(show){
      /** 右边抽屉按钮点击 */
      this.drawerRight.display = show;
    },
    drawerRightClick(){
      /* 点击关闭按钮 */
      this.drawerRight.display=false;
    },

    /** 坐标转换，如果是百度地图，则由BD:09 转换为  EPSG:4326*/
    to4326(pos){
      if (this.isBaidu){
        return transform(pos, 'BD:09','EPSG:4326')
      }else{
        return pos;
      }
    },
    from4326(pos){
      if (this.isBaidu){
        return transform(pos, 'EPSG:4326','BD:09')
      }else{
        return pos;
      }
    }

  },
  computed:{
    drawerRightDisplay(){
      return this.drawerRight.display;
    },
    drawerRightBtnDisplay(){
      return this.drawerRight.display;
    }
  }
};
</script>
<style >



#map {
  width: 100%;
  height: 1000px;
}
</style>
